﻿using Interfaces.Model;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using Microsoft.Extensions.DependencyInjection;
using Models;
using Newtonsoft.Json;
using Services;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Utils;
using WorkPieceDataCapture.ViewModels;

namespace ViewModels
{
    public class vm_Chart_Range : vm_Base
    {
        #region 全局变量与枚举
        private IServiceProvider _serviceProvider;
        WorkPieceDataCaptureRespository respository;
        private SeriesCollection _SeriesData;
        public SeriesCollection SeriesData  //饼图的数据源
        {
            get => _SeriesData;
            set
            {
                _SeriesData = value;
                OnPropertyChanged(nameof(SeriesData));
            }
        }
        private model_SearchCondition _conditions;
        public model_SearchCondition conditions
        {
            get
            {
                return _conditions;
            }
            set
            {
                _conditions = value;
                OnPropertyChanged(nameof(conditions));
            }
        }//查询条件
        private string _Yield;
        public string Yield    //统计产量
        {
            get
            {
                return _Yield;

            }
            set
            {
                _Yield = value;
                OnPropertyChanged(nameof(Yield));
            }
        }
        private List<string> _Labels;
        public List<string> Labels
        {
            get
            {
                return _Labels;
            }
            set
            {
                _Labels = value;
                OnPropertyChanged(nameof(Labels));
            }
        }//X轴信息提示
        #endregion
        #region 事件注册
        public ICommand doSummaryCommand { get; set; }   //执行查询事件
        public ICommand doExportCommand { get; set; }  //执行导出明细数据的事件
        #endregion
        #region 构造与析构函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public vm_Chart_Range(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
            this.respository = new WorkPieceDataCaptureRespository(this._serviceProvider);
            doSummaryCommand = new RelayCommand(doSummary);   //点击查询按钮的事件注册
            doExportCommand = new RelayCommand(doExport);   //执行导出列表的事件注册
            initialize();
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        ~vm_Chart_Range()
        {

        }
        #endregion
        #region 事件
        /// <summary>
        /// 类的初始化
        /// </summary>
        /// <returns></returns>
        public IFuncResult<string> initialize()
        {
            var result = new FuncResult<string>();
            try
            {
                this.conditions = new model_SearchCondition();
                this.conditions.dDate_End = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                this.conditions.dDate_Begin = this.conditions.dDate_End.Value.AddDays(-7);
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        /// <summary>
        /// 执行数据查询
        /// </summary>
        /// <param name="parameter"></param>
        private void doSummary(object parameter)
        {
            try
            {
                var context = this._serviceProvider.GetService<AppDbContext>();
                if (context != null)
                {
                    if (conditions.dDate_Begin > conditions.dDate_End)
                    {
                        MessageBox.Show("开始日期不能大于结束日期！");
                        return;
                    }
                    var list_Final = new List<tb_WorkPieceDataCapture_Realtime>();    //存放最终结果
                    var list_FinalJson = new List<string>();    //存放不同实体类但是相同结构的数据的json
                    #region 如果查询的年月区间包含一个月以内的数据，则需要从实时表里查询数据
                    var nowYearMonth = DateTime.Now.ToString("yyyyMM");
                    if (int.Parse(nowYearMonth) >= int.Parse(conditions.dDate_Begin.Value.ToString("yyyyMM"))
                        && (int.Parse(nowYearMonth) <= int.Parse(conditions.dDate_End.Value.ToString("yyyyMM"))))
                    {
                        var result = this.respository.SearchDataFromRealTimeTable(conditions, context.tb_workpiecedatacapture_realtime);
                        if (result.bSuccess)
                        {
                            if (result.obj_Return.Count > 0)
                            {
                                list_Final.AddRange(result.obj_Return);
                            }
                        }
                        else
                        {
                            MessageBox.Show("从实时数据表中获取数据时出现错误！" + result.strMsg);
                            return;
                        }
                    }
                    #endregion
                    #region 根据起始日期到结束日期的年份确认用到的历史表并执行查询
                    for (var i = conditions.dDate_Begin.Value.Year; i <= conditions.dDate_End.Value.Year; i++)
                    {
                        // 使用新的动态查询方法
                        var yearResult = respository.SearchDataFromHistoryTableByYear(i, conditions);
                        if (yearResult.bSuccess)
                        {
                            yearResult.obj_Return.ForEach(ee =>
                            {
                                list_FinalJson.Add(JsonConvert.SerializeObject(ee));
                            });
                        }
                        else
                        {
                            MessageBox.Show($"从{i}年历史表中获取数据时出现错误！" + yearResult.strMsg);
                            return;
                        }
                    }
                    #endregion
                    list_FinalJson.ForEach(ee =>
                    {
                        list_Final.Add(JsonConvert.DeserializeObject<tb_WorkPieceDataCapture_Realtime>(ee));
                    });
                    var total = list_Final.Count;
                    if (total == 0)
                    {
                        MessageBox.Show("当天没有产量");
                        return;
                    }
                    #region 查询出产量统计
                    var ALL_Total = list_Final.Count();
                    var NG_YCQ = list_Final.Where(ee => ee.FLJ_YCQ_Result == "NG").Count(); //一次圈NG
                    var NG_GLH = list_Final.Where(ee => ee.FLJ_GLH_Result == "NG").Count(); //隔离环NG
                    var NG_ECQ = list_Final.Where(ee => ee.FLJ_ECQ_Result == "NG").Count(); //二次圈NG
                    var NG_KZH = list_Final.Where(ee => ee.FLJ_KZH_Result == "NG").Count(); //安全环NG
                    var NG_SK = list_Final.Where(ee => ee.FLJ_SK_Result == "NG").Count(); //锁扣NG
                    var NG_WM = list_Final.Where(ee => ee.FLJ_WM_Result == "NG").Count(); //外密NG
                    var NG_NMQM = list_Final.Where(ee => ee.JCY_QM_Result == "NG").Count(); //内密气密NG
                    var NG_KTQM = list_Final.Where(ee => ee.JCY_KTQM_Result == "NG").Count(); //壳体气密NG

                    var NG_TOTAL = NG_YCQ + NG_GLH + NG_ECQ + NG_KZH + NG_SK + NG_WM + NG_NMQM + NG_KTQM; //NG总数
                    var NG_YCQ_Percent = MathMethods.CalculatePercentage(NG_YCQ, NG_TOTAL); //一次圈NG百分比
                    var NG_GLH_Percent = MathMethods.CalculatePercentage(NG_GLH, NG_TOTAL); //隔离环NG百分比
                    var NG_ECQ_Percent = MathMethods.CalculatePercentage(NG_ECQ, NG_TOTAL); //二次圈NG百分比
                    var NG_KZH_Percent = MathMethods.CalculatePercentage(NG_KZH, NG_TOTAL); //安全环NG百分比
                    var NG_SK_Percent = MathMethods.CalculatePercentage(NG_SK, NG_TOTAL); //锁扣NG百分比
                    var NG_WM_Percent = MathMethods.CalculatePercentage(NG_WM, NG_TOTAL); //外密NG百分比
                    var NG_NMQM_Percent = MathMethods.CalculatePercentage(NG_NMQM, NG_TOTAL); //内密气密NG百分比
                    var NG_KTQM_Percent = MathMethods.CalculatePercentage(NG_KTQM, NG_TOTAL); //壳体气密NG百分比
                    this.Yield = string.Format("产量：{0}；NG：{1}；一次圈：{2}({3})；隔离环：{4}({5})；二次圈：{6}({7})；安全环：{8}({9})；锁扣：{10}({11})；外密：{12}({13})；内密气密：{14}({15})；壳体气密：{16}({17})；",
                        ALL_Total, NG_TOTAL, NG_YCQ, NG_YCQ_Percent, NG_GLH, NG_GLH_Percent, NG_ECQ, NG_ECQ_Percent, NG_KZH, NG_KZH_Percent, NG_SK, NG_SK_Percent, NG_WM, NG_WM_Percent, NG_NMQM, NG_NMQM_Percent, NG_KTQM, NG_KTQM_Percent);
                    #endregion

                    SeriesData = new SeriesCollection();
                    Labels = new List<string> { "小于-1", "(-1到<-0.9)", "(-0.9到<-0.8)", "(-0.8到<-0.7)", "(-0.7到<-0.6)", "(-0.6到<-0.5)", "(-0.5到<-0.4)", "(-0.4到<-0.3)", "(-0.3到<-0.2)", "(-0.2到<-0.1)", "(-0.1到<0.0)", "(0.0到<0.1)", "(0.1到<0.2)", "(0.2到<0.3)", "(0.3到<0.4)", "(0.4到<0.5)", "(0.5到<0.6)", "(0.6到<0.7)", "(0.7到<0.8)", "(0.8到<0.9)", "(0.9到<1)", "大于上限1" };
                    SeriesData = new SeriesCollection { };
                    switch (this.conditions.FLJ_Type)
                    {
                        case "安全环":
                            #region 安全环
                            ColumnSeries series_KZH = new ColumnSeries();
                            series_KZH.Title = "安全环";
                            series_KZH.Fill = new SolidColorBrush(Color.FromRgb(242, 93, 156));
                            series_KZH.DataLabels = true;
                            series_KZH.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
                            series_KZH.FontSize = 22;
                            //显示文本内容
                            series_KZH.LabelPoint = p => p.Y.ToString();
                            series_KZH.Values = new ChartValues<ObservablePoint>
                            {
                                new ObservablePoint(0, list_Final.Where(ee=>ee.FLJ_KZH_Value< -1).Count()),
                                new ObservablePoint(1,  list_Final.Where(ee=>ee.FLJ_KZH_Value>=-1 && ee.FLJ_KZH_Value<-0.9).Count()),
                                new ObservablePoint(2, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.9 && ee.FLJ_KZH_Value<-0.8).Count()),
                                new ObservablePoint(3, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.8 && ee.FLJ_KZH_Value<-0.7).Count()),
                                new ObservablePoint(4, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.7 && ee.FLJ_KZH_Value<-0.6).Count()),
                                new ObservablePoint(5, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.6 && ee.FLJ_KZH_Value<-0.5).Count()),
                                new ObservablePoint(6, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.5 && ee.FLJ_KZH_Value<-0.4).Count()),
                                new ObservablePoint(7, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.4 && ee.FLJ_KZH_Value<-0.3).Count()),
                                new ObservablePoint(8, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.3 && ee.FLJ_KZH_Value<-0.2).Count()),
                                new ObservablePoint(9, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.2 && ee.FLJ_KZH_Value<-0.1).Count()),
                                new ObservablePoint(10, list_Final.Where(ee=>ee.FLJ_KZH_Value>=-0.1 && ee.FLJ_KZH_Value<-0.0).Count()),
                                new ObservablePoint(11, list_Final.Where(ee => ee.FLJ_KZH_Value >= 0.0 && ee.FLJ_KZH_Value < 0.1).Count()),
                                new ObservablePoint(12, list_Final.Where(ee => ee.FLJ_KZH_Value >= 0.1 && ee.FLJ_KZH_Value < 0.2).Count()),
                                new ObservablePoint(13, list_Final.Where(ee => ee.FLJ_KZH_Value >= 0.2 && ee.FLJ_KZH_Value < 0.3).Count()),
                                new ObservablePoint(14, list_Final.Where(ee=>ee.FLJ_KZH_Value>=0.3 && ee.FLJ_KZH_Value<0.4).Count()),
                                new ObservablePoint(15, list_Final.Where(ee =>ee.FLJ_KZH_Value >= 0.4 && ee.FLJ_KZH_Value < 0.5).Count()),
                                new ObservablePoint(16, list_Final.Where(ee =>ee.FLJ_KZH_Value >= 0.5 && ee.FLJ_KZH_Value < 0.6).Count()),
                                new ObservablePoint(17, list_Final.Where(ee =>ee.FLJ_KZH_Value >= 0.6 && ee.FLJ_KZH_Value < 0.7).Count()),
                                new ObservablePoint(18, list_Final.Where(ee =>ee.FLJ_KZH_Value >= 0.7 && ee.FLJ_KZH_Value < 0.8).Count()),
                                new ObservablePoint(19, list_Final.Where(ee =>ee.FLJ_KZH_Value >= 0.8 && ee.FLJ_KZH_Value < 0.9).Count()),
                                new ObservablePoint(20, list_Final.Where(ee => ee.FLJ_KZH_Value >= 0.9 && ee.FLJ_KZH_Value < 1.0).Count()),
                                new ObservablePoint(21, list_Final.Where(ee =>ee.FLJ_KZH_Value >= 1).Count())
                            };
                            //柱子宽度
                            series_KZH.Width = 50;
                            series_KZH.MaxColumnWidth = 50;
                            #endregion
                            SeriesData.Add(series_KZH);    //安全环  
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    MessageBox.Show("当前无法连接到数据库，请重试一次");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询操作发生异常！\n" + ex.Message);
            }
        }
        /// <summary>
        /// 执行导出列表数据
        /// </summary>
        /// <param name="parameter"></param>
        private void doExport(object parameter)
        {

        }
        #endregion
        #region 方法

        #endregion
    }
}
